// Copyright (c) 2012-2013, yuno. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
package sugarmintcandy.widgetwindow;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

public class MainBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
	Debug.trace("intent=%s", intent);

	String action = intent.getAction();
	if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
	    MainApplication app = getApplication(context);
	    app.getHostManager().cleanAppWidgetIdLeaks();
	    return;
	}
	if (Constants.ACTION_OPEN_WINDOW.equals(action)) {
	    intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
	    context.sendBroadcast(intent);
	    intent = new Intent(context, OpenWindowActivity.class);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
		    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    context.startActivity(intent);
	    return;
	}
	if (Constants.ACTION_SHOW_WINDOW.equals(action)) {
	    int appWidgetId = intent.getIntExtra(Constants.EXTRA_APPWIDGETID,
		    -1);
	    showWindow(context, appWidgetId);
	}
	if (Constants.ACTION_HIDE_WINDOW.equals(action)) {
	    int appWidgetId = intent.getIntExtra(Constants.EXTRA_APPWIDGETID,
		    -1);
	    hideWindow(context, appWidgetId);
	}
	if (Constants.ACTION_HIDE_ALL_WINDOWS.equals(action)) {
	    SharedPreferences prefs = PreferenceManager
		    .getDefaultSharedPreferences(context);
	    int workspace = prefs.getInt(PreferenceKeys.CURRENT_WORKSPACE, 0);
	    hideAllWindows(context, workspace);
	}
	if (Constants.ACTION_SWITCH_WORKSPACE.equals(action)) {
	    int workspace = intent.getIntExtra(Constants.EXTRA_WORKSPACE, 0);
	    intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
	    context.sendBroadcast(intent);
	    if (workspace >= 1 && workspace <= 10) {
		switchWorkspace(context, workspace);
	    }
	    return;
	}
	if (Constants.ACTION_SHOW_NOTICE.equals(action)) {
	    intent.setClass(context, MainService.class);
	    context.startService(intent);
	    return;
	}
	if (Constants.ACTION_LOCALE_FIRE_SETTING.equals(action)) {
	    Bundle bundle = intent
		    .getBundleExtra(Constants.EXTRA_LOCALE_BUNDLE);
	    if (bundle != null) {
		int workspace = bundle.getInt(Constants.LOCALE_WORKSPACE, 0);
		if (workspace >= 1 && workspace <= 10) {
		    switchWorkspace(context, workspace);
		}
		String hideAppWidgetIds = bundle
			.getString(Constants.LOCALE_HIDE_APPWIDGETIDS);
		if (hideAppWidgetIds != null) {
		    for (String id : hideAppWidgetIds.split(" ")) {
			try {
			    hideWindow(context, Integer.parseInt(id));
			} catch (NumberFormatException ex) {
			    Debug.warn(ex);
			}
		    }
		}
		String showAppWidgetIds = bundle
			.getString(Constants.LOCALE_SHOW_APPWIDGETIDS);
		if (showAppWidgetIds != null) {
		    for (String id : showAppWidgetIds.split(" ")) {
			try {
			    showWindow(context, Integer.parseInt(id));
			} catch (NumberFormatException ex) {
			    Debug.warn(ex);
			}
		    }
		}
	    }
	    return;
	}
	if (BillingService.ACTION_RESPONSE_CODE.equals(action)) {
	    MainApplication app = getApplication(context);
	    app.getBillingService().onResponseCode(intent);
	    return;
	}
	if (BillingService.ACTION_IN_APP_NOTIFY.equals(action)) {
	    MainApplication app = getApplication(context);
	    app.getBillingService().onInAppNotify(context, intent);
	    return;
	}
	if (BillingService.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
	    MainApplication app = getApplication(context);
	    app.getBillingService().onPurchaseStateChanged(context, intent);
	    return;
	}
    }

    private static MainApplication getApplication(Context context) {
	return (MainApplication) context.getApplicationContext();
    }

    private void switchWorkspace(Context context, int workspace) {
	SharedPreferences.Editor editor = PreferenceManager
		.getDefaultSharedPreferences(context).edit();
	editor.putInt(PreferenceKeys.CURRENT_WORKSPACE, workspace);
	editor.commit();
    }

    private void showWindow(Context context, int appWidgetId) {
	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(context);
	int workspace = prefs.getInt(PreferenceKeys.CURRENT_WORKSPACE, 0);
	MainDatabase db = getApplication(context).getDatabase();
	WindowInfo info = db.getWindowInfo(appWidgetId);
	if (info != null) {
	    info.workspace |= 1 << workspace;
	    db.updateWindowInfo(info, true);
	}
    }

    private void hideWindow(Context context, int appWidgetId) {
	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(context);
	int workspace = prefs.getInt(PreferenceKeys.CURRENT_WORKSPACE, 0);
	MainDatabase db = getApplication(context).getDatabase();
	WindowInfo info = db.getWindowInfo(appWidgetId);
	if (info != null) {
	    info.workspace &= ~(1 << workspace);
	    db.updateWindowInfo(info, true);
	}
    }

    private void hideAllWindows(Context context, int workspace) {
	MainDatabase db = getApplication(context).getDatabase();
	for (WindowInfo info : db.getWindowInfoList()) {
	    if ((info.workspace & (1 << workspace)) != 0) {
		info.workspace &= ~(1 << workspace);
		db.updateWindowInfo(info, true);
	    }
	}
    }

    public static PendingIntent getOpenWindowPendingIntent(Context context) {
	Intent intent = new Intent(context, MainBroadcastReceiver.class);
	intent.setAction(Constants.ACTION_OPEN_WINDOW);
	return PendingIntent.getBroadcast(context, 0, intent, 0);
    }

    public static PendingIntent getSwitchWorkspacePendingIntent(
	    Context context, int workspace) {
	Intent intent = new Intent(context, MainBroadcastReceiver.class);
	intent.setAction(Constants.ACTION_SWITCH_WORKSPACE);
	intent.putExtra(Constants.EXTRA_WORKSPACE, workspace);
	return PendingIntent.getBroadcast(context, workspace, intent, 0);
    }
}
